﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using CDSBDemandControl.Configuration;
using System.Diagnostics;
using CDSBDemandControl.Model;

namespace CDSBDemandControlServiceAux
{
    class Principal
    {
        #region Properties

        System.Threading.Timer RegularTimer;
        DiscriminatorDemandServiceAux DemandServiceAux;
        
        string WIScenariosAndTasksXMLPath;
        
        bool stillRunning;
        bool writingFiles;

        #endregion

        #region Constructor

        public Principal()
        {
            //Nunca colocar nada no construtor por questão de performance do Start do Serviço
        }

        #endregion

        #region Run

        /// <summary>
        /// Main Start Method
        /// </summary>
        public void Run()
        {
            Initialize();
        }

        #endregion

        #region Initialize

        /// <summary>
        /// Inicializa o Service.
        /// Seta o caminho para cada XML, instancia a classe de serviço e seta os timers.
        /// </summary>
        private void Initialize()
        {
            DemandServiceAux = new DiscriminatorDemandServiceAux();

            stillRunning = true;
            writingFiles = false;

            WIScenariosAndTasksXMLPath = ConfigManager.GetWIScenariosAndTasksXMLPath();
                        
            RegularTimer = new System.Threading.Timer(new TimerCallback(RegularTimerElapsedCallBack));            

            RegularTimer.Change(0, (ConfigManager.GetMinutesToRefresh() * 60000));
        }

        #endregion

        #region Dispose

        /// <summary>
        /// Finaliza a utilização dos objetos
        /// </summary>
        /// <param name="disposing"></param>
        public void Dispose(bool disposing)
        {
            // Tem que ser a primeira linha do dispose pois o Timer.Stop dispara o evento novamente.
            stillRunning = false;

            // Aguarda escrever os últimos arquivos.
            while (writingFiles) { Thread.Sleep(5); }

            RegularTimer.Dispose();
        }

        #endregion

        #region Methods

        /// <summary>
        /// Start Function When Timer.Time
        /// </summary>
        /// <param name="stateInfo"></param>
        private void RegularTimerElapsedCallBack(object stateInfo)
        {
            MontaArquivos();
        }

        private void MontaArquivos()
        {
            if (stillRunning)
            {
                try
                {
                    writingFiles = true;

                    List<ScenarioModel> ScenariosAndTasks = DemandServiceAux.ListScenariosAndTasks();
                    DemandServiceAux.CreateFileofWorkItems(WIScenariosAndTasksXMLPath, ScenariosAndTasks);
                    ScenariosAndTasks.Clear();
                    ScenariosAndTasks = null;
                }
                catch (Exception err)
                {
                    EventLog.WriteEntry("CDSBDemandControlServiceAux", err.StackTrace, EventLogEntryType.Error, 1);
                }

                writingFiles = false;
            }
        }

        #endregion

    }
}
